package com.tuanzi.loan.web.bean.system.workflow;

import static com.tuanzi.loan.business.constants.DictionaryCode.WORKFLOW_CATEGORY;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.List;
import java.util.stream.Collectors;

import javax.annotation.PostConstruct;
import javax.faces.bean.ViewScoped;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.primefaces.event.FileUploadEvent;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.google.common.collect.Lists;
import com.tuanzi.loan.core.aspect.Debug;
import com.tuanzi.loan.vo.request.system.ProcessDefinitionSearchRequest;
import com.tuanzi.loan.web.configuration.JSFListingBean;
import com.tuanzi.loan.web.lazy.system.WorkflowDefinitionLazyDataModel;
import com.tuanzi.loan.workflow.entity.FormBinding;
import com.tuanzi.loan.workflow.service.FormBindingService;
import com.tuanzi.loan.workflow.service.WorkflowManagerService;
import com.tuanzi.loan.workflow.vo.ProcessDefinitionResponse;

import lombok.Data;
import lombok.EqualsAndHashCode;

/**
 * @author Ray 2017/09/22
 */
@Data
@Debug
@Component
@ViewScoped
@EqualsAndHashCode(callSuper = true)
public class WorkflowDefinitionBean extends JSFListingBean<ProcessDefinitionSearchRequest, ProcessDefinitionResponse> {

	private static final long serialVersionUID = -2152778554108785342L;

	@Autowired
	private WorkflowManagerService workflowManagerService;
	@Autowired
	private FormBindingService formBindingService;
	private String deploymentId;
	private String importCategory;
	private byte[] importBpmnContent;
	private List<FormBinding> formBindings;
	private String procDefId;

	@PostConstruct
	private void init() {
		initLazyDataModel();
	}

	public void onReset() {
		initLazyDataModel();
	}

	private void initLazyDataModel() {
		$ = new ProcessDefinitionSearchRequest();
		lazyDataModel = new WorkflowDefinitionLazyDataModel($);
	}

	public void onExport(String procDefId) throws Exception {
		getExternalContext().responseReset();
		getExternalContext().setResponseContentType("multipart/form-data");
		getExternalContext().setResponseHeader("content-disposition", "attachment;filename=workflows.zip");
		workflowManagerService.exportProcessDefinition(Lists.newArrayList(procDefId), getExternalContext().getResponseOutputStream());
		getExternalContext().responseFlushBuffer();
		getFacesContext().responseComplete();
	}

	public void onUploadBpmn(FileUploadEvent event) throws IOException {
		importBpmnContent = IOUtils.toByteArray(event.getFile().getInputstream());
	}

	public void onImport() {
		if (StringUtils.isBlank(importCategory)) {
			addErrorMessage("请选择流程分类");
			return;
		}

		if (importBpmnContent == null || importBpmnContent.length <= 0) {
			addErrorMessage("请上传工作流BPMN文件");
			return;
		}

		workflowManagerService.importProcessDefinition(importCategory, new ByteArrayInputStream(importBpmnContent));
		addSuccessfullyMessage();
	}

	public void onDelete(String procDefId) {
		workflowManagerService.deleteProcessDefinition(procDefId);
		addSuccessfullyMessage();
	}

	public void onSuspend(String procDefId) {
		workflowManagerService.suspendProcessDefinition(procDefId);

	}

	public void onActive(String procDefId) {
		workflowManagerService.activeProcessDefinition(procDefId);
	}

	public void onBatchDelete() {
		workflowManagerService.deleteProcessDefinition(getSelectedProcDefIds());
		addSuccessfullyMessage();
	}

	public void onBatchDisable() {
		workflowManagerService.suspendProcessDefinition(getSelectedProcDefIds());
		addSuccessfullyMessage();
	}

	public void onBatchEnable() {
		workflowManagerService.activeProcessDefinition(getSelectedProcDefIds());
		addSuccessfullyMessage();
	}

	public void onBatchExport() throws Exception {
		getExternalContext().responseReset();
		getExternalContext().setResponseContentType("multipart/form-data");
		getExternalContext().setResponseHeader("Content-Disposition", "attachment;filename=workflows.zip");
		workflowManagerService.exportProcessDefinition(getSelectedProcDefIds(), getExternalContext().getResponseOutputStream());
		getExternalContext().responseFlushBuffer();
		getFacesContext().responseComplete();
	}

	public void onLoadFormBinding() {
		formBindings = formBindingService.findAllByProcDefId(procDefId);
	}

	private List<String> getSelectedProcDefIds() {
		return selectedRecords.parallelStream().map(ProcessDefinitionResponse::getId).map(x -> x.toString()).collect(Collectors.toList());
	}

	@Override
	protected List<String> getDictionaryCodes() {
		return Lists.newArrayList(WORKFLOW_CATEGORY);
	}
}
